<?php

namespace app\admin\controller;

use app\admin\service\GroupReportExportService;
use app\admin\service\WorkersExportService;
use app\admin\service\WorkersImportService;
use app\BaseController;
use app\model\WorkersTaskContinuousEvaluationModel;
use app\model\WorkersTaskFactorScoreModel;
use app\model\WorkersTaskModel;
use app\model\WorkersTaskRatingScaleModel;
use app\model\WorkersTaskUserModel;
use app\model\WorkersTaskUserResultModel;
use app\model\WorkersUserModel;
use think\App;

class Workers extends BaseController
{
    protected $mode;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->mode = new WorkersUserModel();
    }

    /**
     * 教职工人员导入
     * @return bool|string
     */
    public function UserImport(): bool|string
    {
        $this->mode->startTrans();
        try {
            $file = $this->request->param('file');
            $WorkersImportService = new WorkersImportService($this->app);
            if (!$WorkersImportService->import($file,['unit_id' => $this->userData['unit_id']])) throw new \Exception($WorkersImportService->message);
            $this->mode->commit();
            return success([],'导入成功！');
        } catch (\Exception $e) {
            $this->mode->rollback();
            // 上传单文件
            $upload = new \app\common\Upload();
            // 设置上传类型和文件大小
            $upload = $upload->defaultConfig();
            $ext = '.txt';
            $url = $upload->upload($e->getMessage(),'binary',$ext);
            return error('导入失败！',$e->getCode(),[
                'url' => $url
            ]);
        }
    }

    /**
     * 教职工人员选择器
     * @return bool|string
     */
    public function UserSelector(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            if (!empty($param['name'])) {
                $where[] = ['name', 'like', '%' . $param['name'] . '%'];
            }
            $where[] = ['unit_id','=',$this->userData['unit_id']];
            $data = $this->mode->where($where)->select();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 教职工人员详情
     * @return bool|string
     */
    public function UserInfo(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $data = $this->mode->find($id);
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 教职工人员名单
     * @return bool|string
     */
    public function UserList(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            if (!empty($param['name'])) {
                $where[] = ['name','like', '%' . $param['name'] . '%'];
            }
            if (!empty($param['sex'])) {
                $where[] = ['sex','=', $param['sex']];
            }
            if (!empty($param['position_type'])) {
                $where[] = ['position_type','=', $param['position_type']];
            }
            $where[] = ['unit_id','=',$this->userData['unit_id']];
            $query = $this->mode->where($where);
            $data = $query->paginate($param['pageSize'])->toArray();
            $data['ids'] = $query->column('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 添加教职工
     * @return bool|string
     */
    public function UserAdd(): bool|string
    {
        $param = $this->request->param();
        try {
            $this->validate($param,[
                'id_card|身份证号' => [
                    'require',
                    'regex:/^[1-9]\d{5}(18|19|20|21|22)?\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|[Xx])$/'
                ],
                'name|姓名' =>  'require',
            ]);
            if ($this->mode->where('id_card','=',$param['id_card'])->value('id')) throw new \Exception('身份证号重复！');
            $param['time'] = time();
            $param['unit_id'] = $this->userData['unit_id'];
            $this->mode->insert($param);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 编辑教职工
     * @return bool|string
     */
    public function UserUpdate(): bool|string
    {
        $param = $this->request->param();
        try {
            $info = $this->mode->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            if (!empty($param['id_card']) && $info->id_card != $param['id_card']) {
                if (!isIdCard($param['id_card'])) throw new \Exception('身份证号格式错误！');
                $is = $this->mode->where('id_card','=',$param['id_card'])->value('id');
                if ($is) throw new \Exception('身份证号重复！');
            }
            $info->save($param);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 删除教职工
     * @return bool|string
     */
    public function UserDelete(): bool|string
    {
        $id = $this->request->param('id');
        try {
            if (is_array($id)){
                $this->mode->where('id','in',$id)->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
            }else{
                $this->mode->where('id','=',$id)->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
            }
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }


    /**
     * 发布任务
     * @return false|string
     */
    public function releaseTask(): bool|string
    {
        $taskData = $this->request->param('task');
        $rating_scale = $this->request->param('rating_scale');
        $uids = $this->request->param('uids');
        $WorkersTaskModel = new WorkersTaskModel();
        $WorkersTaskModel->startTrans();
        try {
            $this->validate($taskData, [
                'name|任务名称' =>  'require',
            ]);
            if (!empty($taskData['is_time']) && $taskData['is_time'] == 1) {
                if (empty($taskData['start_time']) || empty($taskData['end_time'])) throw new \Exception('请填写开始和结束时间！');
            }else{
                $taskData['status'] = 2;
            }
            $TaskRatingScaleModel = new WorkersTaskRatingScaleModel();
            $TaskUserModel = new WorkersTaskUserModel();
            $TaskContinuousEvaluation = new WorkersTaskContinuousEvaluationModel();
            if (empty($uids) || empty($rating_scale)) throw new \Exception('请选择量表和用户！');
            $rating_scale_column = array_column($rating_scale, 'id');
            if (count($rating_scale_column) !== count(array_unique($rating_scale_column))) throw new \Exception('量表不能重复选择！');
            $taskData['rating_scale_count'] = count($rating_scale);
            $taskData['user_count'] = count($uids);
            $taskData['unit_id'] = $this->userData['unit_id'];
            $taskData['uid'] = $this->userData['id'];
            $taskData['time'] = $time = time();
            if ($taskData['start_time'] >= $time && $taskData['end_time'] <= $time) {
                //在任务时间内将任务设为进行中
                $taskData['status'] = 2;
            }
            if(!empty($taskData['result_read_auth'])){
                $taskData['result_read_auth'] = implode(',',$taskData['result_read_auth']);
            }
            $task_id = $WorkersTaskModel->insertGetId($taskData);
            //添加任务量表和任务用户
            $task_user = [];
            $task_rating_scale = [];
            $continuousData = [];
            foreach ($rating_scale as $item) {
                //预警连续测评
                $factor = $item['factor'] ?? [];
                $factor_id_column = array_column($factor, 'factor_id');
                if (count($factor_id_column) !== count(array_unique($factor_id_column))) throw new \Exception('连评因子不能重复选择！');
                foreach ($factor as $value) {
                    $continuousData[] = [
                        'task_id' => $task_id,
                        'rating_scale_id' => $item['id'],
                        'factor_id' => $value['factor_id'],
                        'continuity_rating_scale_id' => $value['rating_scale_id'],
                        'time' => $time
                    ];
                }
                //任务量表
                $task_rating_scale[] = [
                    'task_id' => $task_id,
                    'rating_scale_id' => $item['id'],
                    'pack_id' => $item['pack_id'],
                    'time' => $time
                ];
                //任务用户
                foreach ($uids as $uid) {
                    $task_user[] = [
                        'task_id' => $task_id,
                        'rating_scale_id' => $item['id'],
                        'uid' => $uid,
                        'time' => $time
                    ];
                }
            }
            if (count($continuousData)) {
                $TaskContinuousEvaluation->insertAll($continuousData);
            }
            if (count($task_user)) {
                $TaskUserModel->insertAll($task_user);
            }
            if (count($task_rating_scale)) {
                $TaskRatingScaleModel->insertAll($task_rating_scale);
            }
            $WorkersTaskModel->commit();
            return success([],'添加成功！');
        } catch (\Exception $e) {
            $WorkersTaskModel->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 删除任务
     * @return false|string
     */
    public function TaskDel(): bool|string
    {
        $id = $this->request->param('id');
        try {
            $WorkersTaskModel = new WorkersTaskModel();
            if (is_array($id)){
                $WorkersTaskModel->where('id','in',$id)->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
            }else{
                $WorkersTaskModel->where('id','=',$id)->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
            }
            return success([],'删除成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 终止任务
     * @return false|string
     */
    public function terminateTask(): bool|string
    {
        $id = $this->request->param('id');
        try {
            $WorkersTaskModel = new WorkersTaskModel();
            $info = $WorkersTaskModel->find($id);
            if ($info->status == 3) return error('任务已终止！');
            $info->status = 3;
            $info->save();
            return success('任务已终止！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 编辑任务
     * @return false|string
     */
    public function TaskUpdate2(): bool|string
    {
        $WorkersTaskModel = new WorkersTaskModel();
        $WorkersTaskModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'task_id|任务ID' => 'require',
                'uid|用户ID' => 'require'
            ]);
            $info = $WorkersTaskModel->find($param['task_id']);
            if (!$info) throw new \Exception('参数错误！');
            $WorkersTaskRatingScaleModel = new WorkersTaskRatingScaleModel();
            $TaskRatingScaleData = $WorkersTaskRatingScaleModel->where('task_id','=', $param['task_id'])->column('rating_scale_id');
            $WorkersTaskUserModel = new WorkersTaskUserModel();
            $uids = $WorkersTaskUserModel->where('task_id','=', $param['task_id'])->column('uid');
            $task_user = [];
            foreach ($param['uid'] as $uid) {
                if (!in_array($uid, $uids)) {
                    foreach ($TaskRatingScaleData as $rating_scale_id){
                        $task_user[] = [
                            'task_id' => $param['task_id'],
                            'rating_scale_id' => $rating_scale_id,
                            'uid' => $uid,
                            'time' => time()
                        ];
                    }
                }
            }
            if (count($task_user)) {
                $WorkersTaskUserModel->insertAll($task_user);
            }
            $info->inc('user_count',count($task_user));
            $info->is_time = $param['is_time']??0;
            $info->end_time = $param['end_time']??0;
            $info->save();
            $WorkersTaskModel->commit();
            return success([],'修改成功！');
        } catch (\Exception $e) {
            $WorkersTaskModel->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 编辑任务
     * @return false|string
     */
    public function TaskUpdate(): bool|string
    {
        $taskData = $this->request->param('task');
        $rating_scale = $this->request->param('rating_scale');
        $uids = $this->request->param('uids');
        $WorkersTaskModel = new WorkersTaskModel();
        $WorkersTaskModel->startTrans();
        try {
            $task_id = $this->request->param('task_id');
            $info = $WorkersTaskModel->find($task_id);
            if (!$info) throw new \Exception('参数错误！');
            if ($info->status != 1) throw new \Exception('未开始的任务才能编辑全部信息！');
            $info->is_del = 1;
            $info->del_time = time();
            $info->save();
            $this->validate($taskData, [
                'name|任务名称' =>  'require',
            ]);
            if (!empty($taskData['is_time']) && $taskData['is_time'] == 1) {
                if (empty($taskData['start_time']) || empty($taskData['end_time'])) throw new \Exception('请填写开始和结束时间！');
            }else{
                $taskData['status'] = 2;
            }
            $TaskRatingScaleModel = new WorkersTaskRatingScaleModel();
            $TaskUserModel = new WorkersTaskUserModel();
            $TaskContinuousEvaluation = new WorkersTaskContinuousEvaluationModel();
            if (empty($uids) || empty($rating_scale)) throw new \Exception('请选择量表和用户！');
            $rating_scale_column = array_column($rating_scale, 'id');
            if (count($rating_scale_column) !== count(array_unique($rating_scale_column))) throw new \Exception('量表不能重复选择！');
            $taskData['rating_scale_count'] = count($rating_scale);
            $taskData['user_count'] = count($uids);
            $taskData['unit_id'] = $this->userData['unit_id'];
            $taskData['uid'] = $this->userData['id'];
            $taskData['time'] = $time = time();
            if ($taskData['start_time'] >= $time && $taskData['end_time'] <= $time) {
                //在任务时间内将任务设为进行中
                $taskData['status'] = 2;
            }
            if(!empty($taskData['result_read_auth'])){
                $taskData['result_read_auth'] = implode(',',$taskData['result_read_auth']);
            }
            unset($taskData['id']);
            $task_id = $WorkersTaskModel->insertGetId($taskData);
            //添加任务量表和任务用户
            $task_user = [];
            $task_rating_scale = [];
            $continuousData = [];
            foreach ($rating_scale as $item) {
                //预警连续测评
                $factor = $item['factor'] ?? [];
                $factor_id_column = array_column($factor, 'factor_id');
                if (count($factor_id_column) !== count(array_unique($factor_id_column))) throw new \Exception('连评因子不能重复选择！');
                foreach ($factor as $value) {
                    $continuousData[] = [
                        'task_id' => $task_id,
                        'rating_scale_id' => $item['id'],
                        'factor_id' => $value['factor_id'],
                        'continuity_rating_scale_id' => $value['rating_scale_id'],
                        'time' => $time
                    ];
                }
                //任务量表
                $task_rating_scale[] = [
                    'task_id' => $task_id,
                    'rating_scale_id' => $item['id'],
                    'pack_id' => $item['pack_id'],
                    'time' => $time
                ];
                //任务用户
                foreach ($uids as $uid) {
                    $task_user[] = [
                        'task_id' => $task_id,
                        'rating_scale_id' => $item['id'],
                        'uid' => $uid,
                        'time' => $time
                    ];
                }
            }
            if (count($continuousData)) {
                $TaskContinuousEvaluation->insertAll($continuousData);
            }
            if (count($task_user)) {
                $TaskUserModel->insertAll($task_user);
            }
            if (count($task_rating_scale)) {
                $TaskRatingScaleModel->insertAll($task_rating_scale);
            }
            $WorkersTaskModel->commit();
            return success([],'添加成功！');
        } catch (\Exception $e) {
            $WorkersTaskModel->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 任务详情
     * @return bool|string
     */
    public function TaskInfo(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $WorkersTaskModel = new WorkersTaskModel();
            $TaskUserModel = new WorkersTaskUserModel();
            $TaskRatingScaleModel = new WorkersTaskRatingScaleModel();
            $TaskContinuousEvaluation = new WorkersTaskContinuousEvaluationModel();
            $task = $WorkersTaskModel->find($id);
            if (!$task) throw new \Exception('参数错误！');
            $task['result_read_auth'] = explode(',',$task['result_read_auth']);
            $uids = $TaskUserModel->where('task_id',$id)->column('uid');
            $uids = array_unique($uids);
            $user_name_list = $this->mode->where('id','in',$uids)->field('id,name')->select()->toArray();
            $TaskRatingScaleList = $TaskRatingScaleModel->where('task_id',$id)
                ->with([
                    'ratingScale',
                    'ratingScalePack'
                ])->select()->toArray();
            $factorList = $TaskContinuousEvaluation->where('task_id',$id)
                ->with([
                    'RatingScale','RatingScaleFactor'
                ])->select()->toArray();
            $factorData = [];
            foreach ($factorList as $item){
                $factorData[$item['rating_scale_id']][] = [
                    'factor_id' => $item['factor_id'],
                    'factor_name' => $item['factor_name'],
                    'rating_scale_id' => $item['rating_scale_id'],
                    'rating_scale_name' => $item['rating_scale_name'],
                ];
            }
            $rating_scale = [];
            foreach ($TaskRatingScaleList as $item){
                $rating_scale[] = [
                    'id' => $item['rating_scale_id'],
                    'name' => $item['rating_scale_name'],
                    'pack_id' => $item['pack_id'],
                    'package' => $item['rating_scale_pack_name'],
                    'factor' => $factorData[$item['rating_scale_id']]??[]
                ];
            }
            return success([
                'task' => $task,
                'uids' => $uids,
                'rating_scale' => $rating_scale,
                'user_name_list' => $user_name_list
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 任务测评报告详情
     * @return bool|string
     */
    public function taskEvaluationReportInfo(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $TaskRatingScaleModel = new WorkersTaskRatingScaleModel();
            $TaskRatingScaleList = $TaskRatingScaleModel->where('task_id','=',$id)
                ->with([
                    'ratingScale'
                ])->select()->toArray();
            $TaskModel = new WorkersTaskModel();
            $TaskInfo = $TaskModel->with([
                'userNameRoleName' => function ($query) {
                    $query->with(['roleName']);
                }
            ])->find($id);
            $TaskInfo['role_name'] = $TaskInfo['role_name']??'超级管理员';
            return success([
                'TaskInfo' => $TaskInfo,
                'TaskRatingScaleList' => $TaskRatingScaleList
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 任务量表详情-左测概况
     * @return bool|string
     */
    public function TaskRatingScaleLeftSurvey(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $TaskRatingScaleModel = new WorkersTaskRatingScaleModel();
            $TaskRatingScaleInfo = $TaskRatingScaleModel->with(['ratingScale', 'task'])->find($id);
            return success($TaskRatingScaleInfo);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 任务测评用户
     * @return bool|string
     */
    public function TaskEvaluationUserDepartment(): bool|string
    {
        $param = $this->request->param();
        try {
            $this->validate($param,[
                'task_id|任务ID' => 'require',
                'rating_scale_id|量表ID' => 'require'
            ]);
            $where = [];
            $user_where = [];
            $result_where = [];
            $where[] = ['task_id','=',$param['task_id']];
            $where[] = ['rating_scale_id','=',$param['rating_scale_id']];
            if (!empty($param['name'])){
                $user_where[] = ['name','like','%'.$param['name'].'%'];
            }
            if (!empty($param['sex'])){
                $user_where[] = ['sex','=',$param['sex']];
            }
            if (!empty($user_where)){
                $uids = $this->mode->where($user_where)->column('id');
                if (!empty($uids)){
                    $where[] = ['uid','in',$uids];
                }else{
                    $where[] = ['id','=',-1];
                }
            }
            if (!empty($param['answer_role'])){
                $result_where[] = ['answer_role','=',$param['answer_role']];
            }
            if (!empty($param['is_warning'])){
                $result_where[] = ['is_warning','=',$param['is_warning']];
            }
            if (!empty($param['is_explain'])){
                $result_where[] = ['is_explain','=',$param['is_explain']];
            }
            if (!empty($param['warning_factor_id'])){
                $WorkersTaskFactorScoreModel = new WorkersTaskFactorScoreModel();
                $result_id = $WorkersTaskFactorScoreModel->where([
                    ['factor_id','=',$param['warning_factor_id']],
                    ['is_warning','=',1]
                ])->column('result_id');
                $result_id = array_unique($result_id);
                if (!empty($result_id)){
                    $result_where[] = ['id','in',$result_id];
                }else{
                    $result_where[] = ['id','=',-1];
                }
            }
            if (!empty($result_where)){
                $WorkersTaskUserResultModel = new WorkersTaskUserResultModel();
                $result_id = $WorkersTaskUserResultModel->where($result_where)->column('id');
                if (!empty($result_id)){
                    $where[] = ['result_id','in',$result_id];
                }else{
                    $where[] = ['id','=',-1];
                }
            }
            $WorkersTaskUserModel = new WorkersTaskUserModel();
            $data = $WorkersTaskUserModel->where($where)
                ->with([
                    'WorkersUser',
                    'WorkersTaskUserResult'
                ])->select()->toArray();

            if (!empty($data)){
                $data2[] = [
                    'id' => 0,
                    'name' => $this->userData['unit']['name'] ?? '',
                    'child' => [],
                    'users' => $data
                ];
            }else{
                $data2 = [];
            }
            return success($data2);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 任务测评报告详情
     * @return bool|string
     */
    public function TaskEvaluationReport(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $TaskUserResultModel = new WorkersTaskUserResultModel();
            $info = $TaskUserResultModel
                ->with([
                    'RatingScale' => function ($query) {
                        $query->with(['ratingScaleTypeName']);
                    },
                    'user' => function ($query) {
                        $query->with(['unitName']);
                    },
                    'RatingScaleFactorWarningModel' => function($query){
                        $query->with(['factorName']);
                    },
                    'TaskFactorScore' => function($query){
                        $query->with([
                            'RatingScaleFactor' => function ($query) {
                                $query->with(['RatingScaleFactorLevel']);
                            },
                            'RatingScaleFactorLevel'
                        ]);
                    }
                ])->find($id);
            if (!$info) throw new \Exception('报告已被删除！');
            return success($info);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 已发布任务列表
     * @return false|string
     */
    public function taskList(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            if (!empty($param['name'])) {
                $where[] = ['name', 'like', '%' . $param['name'] . '%'];
            }
            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where[] = ['time', 'between', [$param['start_time'], $param['end_time']]];
            } else {
                if (!empty($param['start_time'])) {
                    $where[] = ['time', '>=', $param['start_time']];
                }
                if (!empty($param['end_time'])) {
                    $where[] = ['time', '<=', $param['end_time']];
                }
            }
            if (isset($param['status']) && strlen($param['status']) > 0) {
                $where[] = ['status', '=', $param['status']];
            }
            $where[] = ['unit_id','=',$this->userData['unit_id']];
            $WorkersTaskModel = new WorkersTaskModel();
            $query = $WorkersTaskModel->where($where);
            $data = $query->with([
                'userNameRoleName' => function ($query){
                    $query->with(['roleName']);
                }
            ])->order('id desc')->paginate($param['pageSize'])->toArray();
            foreach ($data['data'] as &$item){
                if (empty($item['role_name'])){
                    $item['role_name'] = '超级管理员';
                }
            }
            $data['ids'] = $query->column('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 测评任务报告-删除
     * @return bool|string
     */
    public function TaskResultDel(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $WorkersTaskUserResultModel = new WorkersTaskUserResultModel();
            if (is_array($id)){
                $WorkersTaskUserResultModel->where('id','in',$id)->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
            }else{
                $WorkersTaskUserResultModel->where('id','=',$id)->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
            }
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 测评任务报告-删除单个量表下所有报告
     * @return bool|string
     */
    public function TaskRatingScaleResultDel(): bool|string
    {
        try {
            $task_id = $this->request->param('task_id');
            $rating_scale_id = $this->request->param('rating_scale_id');
            $WorkersTaskUserResultModel = new WorkersTaskUserResultModel();
            $WorkersTaskUserResultModel->where([
                ['task_id','=',$task_id],
                ['rating_scale_id','=',$rating_scale_id]
            ])->update([
                'is_del' => 1,
                'del_time' => time()
            ]);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 获取任务用户
     * @return bool|string
     */
    public function getTaskUser(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $WorkersTaskUserModel = new WorkersTaskUserModel();
            $uids = $WorkersTaskUserModel->where('task_id', '=', $id)->distinct(true)->column('uid');
            if (empty($uids)) return success();
            $finishIds = $WorkersTaskUserModel->where([
                ['task_id', '=', $id],
                ['uid', 'in', $uids],
                ['is_finish', '=', 0]
            ])->column('uid');
            $finishIds = array_unique($finishIds);
            $data = $this->mode->where('id', 'in', $uids)->select()->toArray();
            foreach ($data as &$item) {
                if (in_array($item['id'], $finishIds)) {
                    $item['is_finish'] = 0;
                } else {
                    $item['is_finish'] = 1;
                }
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 获取导入教职工模板
     * @return false|string
     */
    public function getImportTemplate(): bool|string
    {
        return success(['url'=>'/template/workers.xlsx']);
    }

    /**
     * 批量导出教职工
     * @return bool|string
     */
    public function WorkersUserExport(): bool|string
    {
        try {
            $id = $this->request->param('id');
            if (!is_array($id)) throw new \Exception('参数错误！');
            $WorkersExportService = new WorkersExportService($this->app);
            $data = $WorkersExportService->WorkersUserExport($id);
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 任务测评团体报告导出数据
     * @return bool|string
     */
    public function TaskGroupReportExportData(): bool|string
    {
        $task_id = $this->request->param('task_id');
        $rating_scale_id = $this->request->param('rating_scale_id');
        $uid = $this->request->param('uid');
        $GroupReportExportService = new GroupReportExportService($this->app);
        if (!empty($uid)){
            return $GroupReportExportService->WorkersTaskGroupReportExportData($task_id,$rating_scale_id,$uid);
        }else{
            return $GroupReportExportService->WorkersTaskGroupReportExportData($task_id,$rating_scale_id);
        }
    }

    /**
     * 获取任务量表
     * @return false|string
     */
    public function getTaskRatingScale(): bool|string
    {
        $id = $this->request->param('id');
        $WorkersTaskRatingScaleModel = new WorkersTaskRatingScaleModel();
        $data = $WorkersTaskRatingScaleModel->field('id,rating_scale_id')
            ->with(['ratingScale'])
            ->where('task_id', '=', $id)->select()->toArray();
        return success($data);
    }

}